package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"news-manager/cache"
	"news-manager/model"
	"time"
)

func NewList(c *gin.Context) {
	var news []model.News

	err := model.DB.Find(&news).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "列表展示失败",
		})
		return
	}
	redis_key := "news_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &news)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": news,
	})
	return
}
func NewDetail(c *gin.Context) {
	id := c.Query("id")
	var news model.News
	redis_key := "news_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &news)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情展示成功",
		"data": news,
	})
	return
}
